# coding=utf-8
"""
作者：董新强 
创建时间：
描述：
"""
import json

from tornado.gen import coroutine
from tornado.web import RequestHandler

from auth.utils import to_string, to_sha256
from frameworks.db_session import DbSession
from frameworks.resonse_msgs import fail
from models.ceping import Applications

APP_INFO_DICT = {}  # APPID:
with DbSession.create() as db:
    query = db.query(Applications)
    for v in query:
        APP_INFO_DICT[v.app_id] = (v.app_key, json.loads(v.allow_ips, encoding='utf-8'))


class BaseHandler(RequestHandler):
    def __init__(self, application, request, **kwargs):
        super().__init__(application, request, **kwargs)
        self._post_body = None
        self.app_key = None
        self.validated = False  # 是否验证通过(默认不通过

    @coroutine
    def prepare(self):

        try:
            app_id = self.req_dict.get('id', '').strip()
            random_str = self.req_dict.get('rand', '').strip()
            check = self.req_dict.get('check', '').strip()
            if not app_id or not random_str or not check:
                return self.finish(fail(msg='参数错误', hint='参数错误').response)

            item = APP_INFO_DICT.get(app_id)
            if not item:
                return self.finish(fail(msg='没有权限', hint='没有接口权限').response)

            self.app_key, ips = item
            if self.get_client_ip() not in ips:
                return self.finish(fail(msg='没有权限', hint='IP不在白名单中').response)

            if to_sha256(''.join([app_id, self.app_key, random_str])) != check:
                return self.finish(fail(msg='参数错误', hint='参数错误').response)

            self.validated = True  # 验证通过
        except Exception as e:
            print('prepare error=>', e)

    @property
    def req_dict(self):
        if self._post_body:
            return self._post_body

        try:
            self._post_body = json.loads(to_string(self.request.body), encoding='utf-8') or {}
        except:
            dic = {}
            for v in self.request.arguments:
                value = self.request.arguments[v]
                dic[v] = to_string(value[0]) if value else None
            self._post_body = dic
        return self._post_body

    def get_client_ip(self):
        try:
            remote_ip = self.request.headers.get('X-Real-Ip')
            if remote_ip:
                return remote_ip
            return self.request.connection.stream.socket.getpeername()[0]
        except Exception as e:
            print(e)
        return ''
